<?php
/**
 * 用户模块公共函数库
 * Created by PhpStorm.
 * User: Tx
 * Date: 15-4-11
 * Time: 上午9:49
 */

define("APPID", config("EasyWechetConfig")['app_id']);
define("APPSECRET", config("EasyWechetConfig")['secret']);

/**
  *微信函数
 */


//获取微信openid
function get_openid(){

    $openid = session('openid');
    if ( !empty($openid) ) {
        return $openid;
    }

    if (isWeixinBrowser()) {

        $callback = GetCurUrl();
        $access_token = access_token($callback);
        session('openid', $access_token['openid']);
        session('access_token', $access_token);

        return $openid;
    }else{
        return false;
    }

   /* if ( IS_WEIXIN ) {
        $callback = GetCurUrl();
        $openid = OAuthWeixin($callback);
        session('openid', $openid);
        return $openid;
    }else{
        return false;
    }*/
}

// 判断是否是在微信浏览器里
function isWeixinBrowser() {
    $agent = $_SERVER ['HTTP_USER_AGENT'];
    if (! strpos ( $agent, "icroMessenger" )) {
        return false;
    }
    return true;
}

// php获取当前访问的完整url地址
function GetCurUrl() {

    $url = 'http://';

    if ($_SERVER ['SERVER_PORT'] != '80') {
        // $url .= $_SERVER ['HTTP_HOST'] . ':' . $_SERVER ['SERVER_PORT'] . $_SERVER ['REQUEST_URI']; //由于是HTTPS 所以去掉端口号
        $url .= $_SERVER ['HTTP_HOST']. $_SERVER ['REQUEST_URI'];
    } else {
        $url .= $_SERVER ['HTTP_HOST'] . $_SERVER ['REQUEST_URI'];
    }
    // 兼容后面的参数组装
    if (stripos ( $url, '?' ) === false) {
        $url .= '?t=' . time ();
    }
    return $url;
}




// 网页授权获取用户openid
function OAuthWeixin($callback) {
    $isWeixinBrowser = isWeixinBrowser ();
    if($isWeixinBrowser) {

        $param ['appid'] =APPID;
        if (! isset ( $_GET ['getOpenId'] )) {
            $param ['redirect_uri'] = $callback ."&getOpenId=1";
            $param ['response_type'] = 'code';
            $param ['scope'] = 'snsapi_userinfo';
            $param ['state'] = 123;
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query ( $param ) . '#wechat_redirect';

            Header("Location: $url");//重定向

        } elseif ($_GET ['state']) {


            $param ['secret'] =APPSECRET;
            $param ['code'] = $_GET ['code'];

            $param ['grant_type'] = 'authorization_code';
            $url = 'https://api.weixin.qq.com/sns/oauth2/access_token?' . http_build_query ( $param );


            session('code',$param ['code']);
            $content = file_get_contents ( $url );
            $content = json_decode ( $content, true );

            return $content ['openid'];

        }

    }
}

//微信JS配置
function jsSDK(){

    $jssdk = new \WxJsSdk(APPID,APPSECRET);
    $signPackage = $jssdk->GetSignPackage();
    $wxjs['appId']=$signPackage["appId"];
    $wxjs['timestamp']=$signPackage["timestamp"];
    $wxjs['nonceStr']=$signPackage["nonceStr"];
    $wxjs['signature']=$signPackage["signature"];
    return $wxjs;
}



function access_token($callback) {


    $access_token= session('access_token');
    if ( !empty($access_token) ) {
        return $access_token;
    }

    $isWeixinBrowser = isWeixinBrowser ();
    if($isWeixinBrowser) {

        $param ['appid'] =APPID;
        if (! isset ( $_GET ['getOpenId'] )) {
            $param ['redirect_uri'] = $callback ."&getOpenId=1";
            $param ['response_type'] = 'code';
            $param ['scope'] = 'snsapi_userinfo';
            $param ['state'] = 123;
            $url = 'https://open.weixin.qq.com/connect/oauth2/authorize?' . http_build_query ( $param ) . '#wechat_redirect';
            Header("Location: $url");//重定向

        } elseif ($_GET ['state']) {
            $param ['code'] = $_GET ['code'];
            $param ['grant_type'] = 'authorization_code';
            $url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".APPID."&secret=".APPSECRET."&code=".$param ['code']."&grant_type=authorization_code";
            $content = file_get_contents ( $url );
            $content = json_decode ( $content, true );

            return $content;

        }

    }
}

function get_wxUser_info(){

    $callback = GetCurUrl();
    $access_token = access_token($callback);

    $url = "https://api.weixin.qq.com/sns/userinfo?access_token=" . $access_token['access_token'] . "&openid=" . $access_token['openid']. "&lang=zh_CN";
    $rs = json_decode(file_get_contents($url), true);



    return $rs;
}

//获取access_token
function getAccessToken()
{
    $requestUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" . APPID . "&secret=" . APPSECRET;
    $res = http_request($requestUrl, "");
    $res = json_decode($res);
    return $res->access_token;

}




//获取用户信息
function get_userinfo()
{

    $token =getAccessToken();
    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . get_openid() . "&lang=zh_CN";
    $rs = json_decode(file_get_contents($url), true);
    return $rs;
}


//获取用户信息
function get_userinfo_2($data)
{
    $token =getAccessToken();
    $url = "https://api.weixin.qq.com/cgi-bin/user/info?access_token=" . $token . "&openid=" . $data . "&lang=zh_CN";
    $rs = json_decode(file_get_contents($url), true);
    return $rs;
}


//发送客服消息
function send_Service($data){

    $requestUrl = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token=".getAccessToken();
    $rs=http_request($requestUrl,$data);
    if(json_decode($rs,true)['errmsg']=='ok'){
        return true;
    }else{
        return false;
    }
}


//发送模板消息
function send_Template_Message($template){

    $requestUrl = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($template)));

    if(json_decode($rs,true)['errmsg']=='ok'){
        return true;
    }else{
        return false;
    }
}


//发送模板消息
function get_facility($arr){

    $requestUrl = "https://api.weixin.qq.com/shakearound/user/getshakeinfo?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);

}


//微信菜单
function create_menu($button,$matchrule=null){
    if(!is_array($button) || empty($button)){
        return false;
    }
    $button=array_map_recursive('urlencode',$button);

    if(is_array($matchrule)){
        $matchrule=array_map('urlencode',$matchrule);
        $data=urldecode(json_encode(array('button'=>$button,'matchrule'=>$matchrule)));
        $url='https://api.weixin.qq.com/cgi-bin/menu/addconditional?access_token='.getAccessToken();
    }else{
        $data=urldecode(json_encode(array('button'=>$button)));
        $url='https://api.weixin.qq.com/cgi-bin/menu/create?access_token='.getAccessToken();
    }
    $res=http_request($url,$data);
    return json_decode($res,true);
}


function array_map_recursive($filter, $data) {
    $result = array();
    foreach ($data as $key => $val) {
        $result[$key] = is_array($val)
            ? array_map_recursive($filter, $val)
            : call_user_func($filter, $val);
    }
    return $result;
}


/**
 * 创建分组
 */
function create_group($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/device/group/add?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}

/**
 * 查询分组列表
 * @param $arr
 * @return mixed
 */
function get_group_list($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/device/group/getlist?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}

/**
 * 查询分组详细信息
 * @param $arr
 * @return mixed
 */
function get_group_info($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/device/group/getdetail?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}


/**
 * 添加设备到分组
 * @param $arr
 * @return mixed
 */
function add_device_group($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/device/group/adddevice?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}


/**
 * 获取摇一摇页面列表
 * @param $arr
 * @return mixed
 */
function getPageList($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/page/search?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}

/**
 * 添加摇一摇页面
 * @param $arr
 * @return mixed
 */
function setPage($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/page/add?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}


/**
 * 删除摇一摇页面
 * @param $arr
 * @return mixed
 */
function delPage($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/page/delete?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}


/**
 * 配置设备与页面的关联关系
 * @param $arr
 * @return mixed
 */
function relevance($arr){
    $requestUrl = "https://api.weixin.qq.com/shakearound/device/bindpage?access_token=".getAccessToken();
    $rs=http_request($requestUrl,urldecode(json_encode($arr)));
    return json_decode($rs,true);
}


/**
    * 创建二维码ticket 和换取二维码
* @param $data
* @return bool|string
    *
 */
function get_qrcode($data)
{

    $token =getAccessToken();
    $url = "https://api.weixin.qq.com/cgi-bin/qrcode/create?access_token=".$token;
    $rs=http_request($url,urldecode(json_encode($data)));

    $ticket= json_decode($rs,true);

    $url= "https://mp.weixin.qq.com/cgi-bin/showqrcode?ticket=".$ticket['ticket'];
    $requestUrl= file_get_contents($url);
    return $requestUrl;
}


/**
 * 上传素材
 * @param $filepath
 * @return mixed
 */
function add_material($filepath,$type='image'){
    $wx_url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token=".getAccessToken()."&type=".$type;
    $result = http_post($wx_url, $filepath);
    $arr = json_decode($result,true);
    return $arr;
}


//curl
function http_request($url, $data = null)
{
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
    curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
    if (!empty($data)){
        curl_setopt($curl, CURLOPT_POST, 1);
        curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    }
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}




function http_post($url ='' , $fileurl = '' )
{
    $curl = curl_init();
    if(class_exists('\CURLFile')){
        curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, true);
        $data = array('media' => new \CURLFile($fileurl));
    }else{
        if (defined ( 'CURLOPT_SAFE_UPLOAD' )) {
            curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false );
        }
        $data = array('media' => '@' . realpath($fileurl));
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

/**Start**************启用微信开发者配置连接*****************************/


function checkSignature($token)
{

    // you must define TOKEN by yourself
    if (!$token) {

        throw new Exception('TOKEN is not defined!');
    }

    $signature = $_GET["signature"];
    $timestamp = $_GET["timestamp"];
    $nonce = $_GET["nonce"];

    $tmpArr = array($token, $timestamp, $nonce);
    // use SORT_STRING rule
    sort($tmpArr, SORT_STRING);
    $tmpStr = implode( $tmpArr );
    $tmpStr = sha1( $tmpStr );

    if( $tmpStr == $signature ){
        return true;
    }else{
        return false;
    }
}

/**End***************启用微信开发者配置连接*****************************/